package com.derbysoft.defender.controller;

import com.derbysoft.defender.mp.api.AccessTokenHolder;
import com.derbysoft.defender.mp.api.response.AccessToken;
import com.derbysoft.defender.util.WebUtil;
import com.derbysoft.defender.web.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;

/**
 * <p>some description here.</p>
 * Created by Afee Lee on 2017-03-26 11:36
 *
 * @author Afee Lee
 * @version 1.0
 * @see Object
 * @since 1.8
 */
public abstract class AbstractController {
    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractController.class);

    @Value("${weChat.account.appId}")
    private String appId;
    @Value("${weChat.account.appSecret}")
    private String appSecret;

    protected AccessToken getAccessToken() {
        return AccessTokenHolder.getAccessToken(appId, appSecret);
    }

    @ExceptionHandler(Exception.class)
    public void handleException(Exception e, HttpServletResponse response) {
        if (e instanceof IllegalArgumentException) {
            WebUtil.response(response, HttpResponse.newParamErrorResponse(e.getMessage()));
        } else {
            LOGGER.error("500 exception", e);
            WebUtil.response(response, HttpResponse.newServerErrorResponse(e.getMessage()));
        }
    }
}
